package com.dinglian.ots.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.dinglian.ots.common.HttpRequest;
import com.dinglian.ots.common.RelativeDateFormat;
import com.dinglian.ots.common.SendCode;
import com.dinglian.ots.common.ToolUtils;
import com.dinglian.ots.common.model.Constant;
import com.dinglian.ots.dao.mapper.*;
import com.dinglian.ots.dao.model.*;
import com.dinglian.ots.exception.GlobalException;
import com.dinglian.ots.redis.CodeKey;
import com.dinglian.ots.redis.RedisService;
import com.dinglian.ots.result.CodeMsg;
import com.dinglian.ots.service.CommonService;
import com.dinglian.ots.vo.address.CityVo;
import com.dinglian.ots.vo.address.DistrictVo;
import com.dinglian.ots.vo.address.ProvinceVo;
import com.dinglian.ots.vo.buyer.MessageVo;
import com.dinglian.ots.vo.product.*;
import com.dinglian.ots.vo.user.LoginByPasswordVo;
import com.dinglian.ots.vo.user.UserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.tools.Tool;
import java.util.*;

/**
 * @author wangbo
 */
@Service
public class CommonServiceImpl implements CommonService {

    @Value("${pic.path}")
    private String path;

    @Value("${pic.url}")
    private String url;

    @Autowired
    private RedisService redisService;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ParameterMapper paramMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private SeasonMapper seasonMapper;

    @Autowired
    private ColorMapper colorMapper;

    @Autowired
    private SizeMapper sizeMapper;

    @Autowired
    private CountryMapper countryMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Override
    public String sendCode(String mobile) {
        //生成4位验证码
        String code = ToolUtils.createCode(4);
        //发送短信
        SendCode.send(mobile,code);

        //保存到redis  暂时15天
        redisService.set(CodeKey.getKey,mobile,code);
        return code;
    }

    @Override
    public void checkCode(String mobile,String code) {
        boolean isExist = redisService.exists(CodeKey.getKey, mobile);
        if (!isExist) {
            throw new GlobalException(CodeMsg.CODE_EXPIRED);
        }
        //从redis中获取正确的验证码
        String rightCode = redisService.get(CodeKey.getKey, mobile, String.class);
        if (!rightCode.equals(code)) {
            throw new GlobalException(CodeMsg.CODE_ERROR);
        }
    }

    @Override
    public List<CategoryVo> getCategoryList() {
        return categoryMapper.getCategoryList();
    }

    @Override
    public List<ProductCategoryVo> getSubcategoryList() {

        List<ProductCategoryVo>  productCategoryList = categoryMapper.getOneCategoryList();
        for (int i = 0; i < productCategoryList.size(); i++) {
            ProductCategoryVo productCategoryVo = productCategoryList.get(i);
            Integer categoryId = productCategoryVo.getCategoryId();
            List<ProductSubcategoryVo> productSubcategoryList = categoryMapper.getSubcategoryList(categoryId);
            productCategoryVo.setSubcategoryList(productSubcategoryList);
        }
        return productCategoryList;
    }

    @Override
    public List<StyleVo> getStyleList() {
        return paramMapper.getStyleList();
    }

    @Override
    public List<CrowdVo> getCrowdList() {
        return paramMapper.getCrowdList();
    }

    @Override
    public List<SeasonVo> getSeasonList() {
        return seasonMapper.getSeasonList();
    }

    @Override
    public List<ColorVo> getColorList() {
        return colorMapper.getColorList();
    }

    @Override
    public List<SizeVo> getSizeList() {
        return sizeMapper.getSizeList();
    }

    @Override
    public PageInfo<MessageVo> getMessageList(Integer userId,Integer pageNum,Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);
        MessageExample messageExample = new MessageExample();
        messageExample.or().andUserIdEqualTo(userId).andIsDeleteEqualTo(false);
        messageExample.setOrderByClause("create_time desc");
        List<Message> messages = messageMapper.selectByExample(messageExample);

        List<MessageVo> messageVos = new ArrayList<>();

        for (int i = 0; i < messages.size(); i++) {
            Message message = messages.get(i);
            MessageVo messageVo = new MessageVo();
            messageVo.setId(message.getId());
            messageVo.setRead(message.getIsRead());
            messageVo.setMessage(message.getMessage());
            messageVo.setTitle(message.getTitle());
            Date createTime = message.getCreateTime();
            String sendTime = RelativeDateFormat.format(createTime);
            messageVo.setSendTime(sendTime);
            messageVos.add(messageVo);
        }
        return new PageInfo<>(messageVos);
    }

    @Override
    public void deleteMessage(Integer messageId) {
        Message message = new Message();
        message.setId(messageId);
        message.setIsDelete(true);
        message.setLastUpdateTime(DateUtil.date());
        messageMapper.updateByPrimaryKeySelective(message);
    }

    @Override
    public String uploadPicture(MultipartFile file) {
        return url+ToolUtils.uploadPicture(path, "", Constant.PRODUCT_THUMBNAIL, file);
    }

    @Override
    public List<Country> getCountry() {
        CountryExample countryExample = new CountryExample();
        countryExample.createCriteria();
        return countryMapper.selectByExample(countryExample);
    }


    @Override
    public List<ProvinceVo> getProvinceCity() {
        List<Map> list = districtMapper.getProvinceCity();
        List<ProvinceVo> provinceVos = new ArrayList<>();

        Map provinceMap = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            Map map = list.get(i);
            Integer cityId = (Integer) map.get("cityId");
            String cityName = (String) map.get("cityName");
            Integer provinceId = (Integer) map.get("provinceId");
            String provinceName = (String) map.get("provinceName");

            CityVo cityVo = new CityVo();
            cityVo.setId(cityId);
            cityVo.setName(cityName);
            cityVo.setPid(provinceId);

            ProvinceVo provinceVo = (ProvinceVo) provinceMap.get(provinceId);
            if (provinceVo == null){
                provinceVo = new ProvinceVo();
                provinceVo.setId(provinceId);
                provinceVo.setName(provinceName);
                List<CityVo> cityVos = new ArrayList<>();
                cityVos.add(cityVo);
                provinceVo.setCityList(cityVos);
                provinceMap.put(provinceId,provinceVo);
                provinceVos.add(provinceVo);
            }else{
                List<CityVo> cityList = provinceVo.getCityList();
                cityList.add(cityVo);
            }
        }

        return provinceVos;
    }


    @Override
    public List<District> getChildDistrict(Integer parentId) {
        DistrictExample districtExample = new DistrictExample();
        districtExample.or().andPidEqualTo(parentId);
        List<District> districts = districtMapper.selectByExample(districtExample);

        return districts;
    }
}
